<template>
  <div style="height: 100%">
    <van-field
      v-model="fieldValue"
      :is-link="isLink"
      readonly
      :disabled="disabled"
      :required="required"
      :label="label"
      :input-align="inputAlign"
      :rules="[{ required: required, message: message }]"
      :placeholder="placeholder"
      @click="clickAreaSelect"
    >
      <template v-if="customRightIcon && !isLink" #right-icon>
        <img src="../../assets/img/common/areaSelectIcon.png" alt="" />
      </template>
    </van-field>
    <van-popup v-model:show="show" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :field-names="{ text: 'name', value: 'id', children: 'children' }"
        :options="options"
        @close="show = false"
        @change="onChange"
        @finish="onFinish"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from 'vue'
import { gerAreaByCode } from '@/api/api.js'
import { useUserStore } from '@/pinia/modules/user'

const emit = defineEmits(['update:value', 'change'])
const props = defineProps({
  value: {
    type: [Array, String]
  },
  // label名称
  label: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  // 是否必填
  required: {
    type: Boolean,
    default: false
  },
  // 提示语
  message: {
    type: String,
    default: '请选择'
  },
  isLink: {
    type: Boolean,
    default: true
  },
  // 最终值是否只展示最后一级
  valueIsLast: {
    type: Boolean,
    default: false
  },
  customRightIcon: {
    type: Boolean,
    default: false
  },
  maxSelectLevel: {
    // 最大可选择级别 -1无限制 1省级 2市级 3区县级 4街道乡镇 5社区村
    type: [String, Number],
    default: -1
  },
  isLimitCurrentAccount: {
    // true 限制选择范围为当前用户所属级别及以下区划； false 自由选择所有区划
    type: Boolean,
    default: false
  },
  currentCode: {
    type: [String, Number],
    default: ''
  },
  currentName: {
    type: String,
    default: ''
  },
  inputAlign: {
    type: String,
    default: 'left'
  },
  initCode: {
    type: String,
    default: '440000000000'
  },
  areaType: {
    type: String,
    default: 'register'
  }
})

const show = ref(false)
const fieldValue = ref('')
const cascaderValue = ref('')
const disabled = ref(false)
const options = ref([])
const currentLevel = ref(1)
const state = reactive({
  areaCodeArray: []
})

const addTree = (selectedOptions, children, id) => {
  selectedOptions.forEach(item => {
    if (item.id == id) {
      item.children = children
    }
  })
}

const clickAreaSelect = () => {
  // if (
  //   props.maxSelectLevel > 0 &&
  //   props.maxSelectLevel == useUserStore().orgInfo.level
  // ) {
  //   disabled.value = true
  //   return
  // }
  show.value = true
}

const onChange = async ({ value, selectedOptions, tabIndex }) => {
  let res = await getNextArea(value)
  if (res.succeed && res.data.length > 0) {
    if (
      (props.maxSelectLevel == 5 && res.data[0]?.level > 5) ||
      (props.maxSelectLevel == 4 && res.data[0]?.level > 4) ||
      (props.maxSelectLevel == 3 && res.data[0]?.level > 3) ||
      (props.maxSelectLevel == 2 && res.data[0]?.level > 2) ||
      (props.maxSelectLevel == 1 && res.data[0]?.level > 1)
    ) {
      show.value = false
      return false
    }
    addTree(selectedOptions, res.data, value)
  } else {
    show.value = false
  }
}

const onFinish = ({ selectedOptions }) => {
  if (props.valueIsLast) {
    fieldValue.value = selectedOptions[selectedOptions.length - 1].name
  } else {
    fieldValue.value = selectedOptions.map(option => option.name).join('/')
  }

  let arr = selectedOptions.map(option => option.id)
  let code = selectedOptions[selectedOptions.length - 1].id
  emit('update:value', code)
  emit('change', code)
}

const getNextArea = async code => {
  let res = await gerAreaByCode(code)
  if (res.succeed) {
    return res
  }
}

const getFirstArea = async code => {
  let res = await getNextArea(code)
  let arr = []
  if (res.data && res.data.length > 0) {
    arr = res.data.filter(item => {
      return item.id == props.initCode
    })
  }

  let res2 = await getNextArea(arr[0].id)
  arr[0].children = res2.data
  options.value = arr
}

onBeforeMount(() => {
  // ['440000000000','440100000000']
  // getFirstArea(props.currentCode || useUserStore().userLastArea)
  // fieldValue.value = props.currentName || useUserStore().userLastName
  // 放开所有选择权限 其他控制选择均无效
  if (props.isLimitCurrentAccount) {
    getFirstArea('000000')
  } else {
    getFirstArea('000000')
  }
  
  cascaderValue.value = '440000000000'

  if (props.value) {
    // 默认值回显
    if (props.areaType == 'register') {

    } else if (props.areaType == 'live') {

    } else {
    }
    cascaderValue.value = ['440000000000']
  }
})
</script>
<style lang="less" scoped>
:deep(.van-cell) {
  align-items: center;
}
:deep(.van-field__right-icon) {
  display: flex;
  align-items: center;
  img {
    width: 20px;
  }
}
:deep(.van-field__body) {
  font-size: 28px;
}
:deep(.van-field__right-icon) {
  padding: 0;
  margin-right: 8px;
}
:deep(.van-field__control::-webkit-input-placeholder) {
  color: #000;
}
</style>
